package com.yuwenchao.superafflatus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuwenchao.superafflatus.constant.AfflatusConstant;
import com.yuwenchao.superafflatus.pojo.entity.SuperSalary;
import com.yuwenchao.superafflatus.service.SuperSalaryService;
import com.yuwenchao.superafflatus.utils.DownloadUtils;
import com.yuwenchao.superafflatus.utils.IREUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chaooGG
 * @version 1.0
 * @date 2021/6/18 13:57
 */
@Slf4j
@Api(tags = "系统文件上传下载")
@Controller
public class FunctionDULoadController {


    //从配置文件中取路径值
    @Value("${linuxFile.downloadFile}")
    private String downloadFile;


    @Value("${linuxFile.ExcelModel}")
    private String ExcelModel;

    @Value("${linuxFile.DownCalc}")
    private String DownCalc;

    @Value("${linuxFile.DownSql}")
    private String DownSql;

    @Value("${linuxFile.upladFile}")
    private String upladFile;

    @Value("${linuxFile.iReport}")
    private String iReport;


    @Autowired
    SuperSalaryService salaryService;

//本地文件下载
    @ApiOperation(value = "Excel模板下载功能")
    @GetMapping("/ExcelModel")
    public void down(HttpServletResponse response,String URL) throws Exception {
        DownloadUtils.DownloadFile(AfflatusConstant.DOWNLOAD_EXCELMODEL, response);

    }

    @ApiOperation(value = "多功能理财计算器下载")
    @GetMapping("/downCalculator")
    public void downCalculator(HttpServletResponse response,String URL){
        DownloadUtils.DownloadFile(AfflatusConstant.DOWNLOAD_CALCULATOR, response);
    }


    @ApiOperation(value = "数据库文件下载")
    @GetMapping("/downSQL")
    public void downloadSQLFile(HttpServletResponse response,String URL){

        DownloadUtils.DownloadFile(AfflatusConstant.DOWNLOAD_SQLFILE, response);
    }


    /*
	 * 1.报表字体统一改为宋体
	 * 2.关于报表打印如果控制台报错Unknown property ' ' on class
	 * 需要删除修改.jrxml文件中的这个字段
	   <fieldDescription><![CDATA[]]></fieldDescription>
	   3.报表的字段属性和VO属性保持一致。
	   *
	   4.Springboot项目预览ireport报表，jasper文件不建议放在项目路径中。
	   * 模板文件建议放在环境目录中方便调用，防止切换环境 导致路径获取失败。
	   *
	 */

    @PreAuthorize("hasRole('ROLE_admin')")
    @ApiOperation(value = "iReport预览")
    @GetMapping("SalaryPDF")
    public void showAllSalary(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("title", "个人资产信息详情");

        //获取用户名信息
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        params.put("username", username);
        QueryWrapper<SuperSalary> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("month","income","amount");
        List<SuperSalary> list = salaryService.list(queryWrapper);

       // String filePath = ClassUtils.getDefaultClassLoader().getResource(AfflatusConstant.SHOW_SALARYPDF).getPath();
        //文件路劲/E:/superafflatus/target/classes/static/DownloadFile/AfflatusSalary.jasper
        //log.info("项目文件路劲"+filePath);

        //如果把文件放在环境中
        String filePath1 = iReport;
        log.info("环境文件路劲"+filePath1);

       /* ServletContext servletContext =request.getSession().getServletContext();
        System.out.println("路径："+servletContext);
        String filePath = servletContext.getRealPath("static/filemodel/YearSalary.jasper");
        System.out.println("路径："+filePath);*/

        IREUtils.printToPdfView(response, filePath1, params, list);

    }

    //linux服务器下载   这里的linux指的是将路径更换为linux环境的路径了
    @ApiOperation(value = "Excel模板文件linux下载")
    @GetMapping("/LinuxExcelModel")
    public void LinuxExcelModel(HttpServletResponse response) throws IOException {
        //该方法下载中文文件时获取不到中文文件名称
        //response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(TxtName, "UTF-8"));
        String fileName ="model.xlsx";
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        //linux版
        System.out.println("获取到的文件名"+fileName);
        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
           // FileInputStream inputStream = new FileInputStream(downloadFile+fileName);
           // 取非项目环境下的文件
            FileInputStream inputStream = new FileInputStream(ExcelModel);

            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }



    @PreAuthorize("hasRole('ROLE_admin')")
    @ApiOperation(value = "数据库linux下载")
    @GetMapping("/LinuxSQLModel")
    public void LinuxSQLModel(HttpServletResponse response) throws IOException {
        //该方法下载中文文件时获取不到中文文件名称
        //response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(TxtName, "UTF-8"));
        String fileName ="afflatus.sql";
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        //linux版
        System.out.println("获取到的文件名"+fileName);
        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
            FileInputStream inputStream = new FileInputStream(downloadFile+fileName);
            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }


    @ApiOperation(value = "计算器linux下载")
    @GetMapping("/LinuxCalcModel")
    public void LinuxCalcModel(HttpServletResponse response) throws IOException {
        //该方法下载中文文件时获取不到中文文件名称
        //response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(TxtName, "UTF-8"));
        String fileName ="计算器.zip";
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        //linux版
        System.out.println("获取到的文件名"+fileName);
        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
            FileInputStream inputStream = new FileInputStream(downloadFile+fileName);
            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }



    @ApiOperation(value = "多文件上传")
    @PostMapping("/Ajaxupload")
    @ResponseBody
    public Map upload(MultipartFile[] file, HttpSession session) {
        //获取服务器上传的文件路径
        // String dir =  session.getServletContext().getRealPath("/upload");
        Map<String, Object> resultmap = new HashMap<>();


        String dir = upladFile;
        //String dir = AfflatusConstant.UPLOAD_PATH;
        Map<String,Object> map=new HashMap<>();
        if(file.length==1) {
            System.out.println("上传了一个文件");
            //文件类型
            String type = file[0].getContentType();
            //文件名
            String filename = file[0].getOriginalFilename();
            //文件的后缀名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            //文件大小
            long filesize1 =  file[0].getSize()/1024;
            if(filesize1<1024) {
                filesize1=filesize1+1;
            }
            String filesize =filesize1+"KB";
            map.put("文件名",filename);
            // map.put("文件格式",suffix);
            map.put("文件大小",filesize);
            map.put("文件路劲",dir);

            //创建要保存文件的路径
            File dirFile = new File(dir,filename);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            try {
                //将文件写入创建的路径
                file[0].transferTo(dirFile);
                System.out.println("文件保存成功!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return  map;

            // return R.ok().data("map", map);
        }else {
            List<String> list =	new ArrayList<>();
            for (int i = 0; i < file.length; i++) {
                String type = file[i].getContentType();
                String filename = file[i].getOriginalFilename();
                //获取文件的后缀名
                String suffix = filename.substring(filename.lastIndexOf(".") + 1);

                long size = file[i].getSize()/1024+1;
                if(size<1024) {
                    size=size+1;
                }
                String filesize =size+"KB";

                //list.add(type);
                list.add(filename);
                list.add(suffix);
                list.add(filesize);

                //创建要保存文件的路径
                File dirFile = new File(dir,filename);
                if (!dirFile.exists()){
                    dirFile.mkdirs();
                }
                try {
                    //将文件写入创建的路径
                    file[i].transferTo(dirFile);
                    System.out.println("文件保存成功!");
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            map.put("dir",dir);
            map.put("list", list);

            return  map;
            //  return R.ok().data("map", map);

        }
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload/UploadAction")
    @ResponseBody
    public Map upload(MultipartFile file) {

        //String dir =AfflatusConstant.UPLOAD_PATH;
        String dir= upladFile;
        Map<String,Object> map=new HashMap<>();

        //文件类型
        String type = file.getContentType();
        //文件名
        String filename = file.getOriginalFilename();
        //文件的后缀名
        String suffix = filename.substring(filename.lastIndexOf(".") + 1);
        //文件大小
        long filesize1 =  file.getSize()/1024;
        if(filesize1<1024) {
            filesize1=filesize1+1;
        }
        String filesize =filesize1+"KB";
        map.put("filename",filename);
        map.put("suffix",suffix);
        map.put("filesize",filesize);
        map.put("dir",dir);

        //创建要保存文件的路径
        File dirFile = new File(dir,filename);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        try {
            //将文件写入创建的路径
            file.transferTo(dirFile);
            log.info("上传成功，文件保存至"+dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  map;

    }


}
